package com.blue.base.shiro.filter;

import cn.hutool.http.HttpStatus;
import com.blue.base.common.exception.ShiroUnAuthorizedException;
import com.blue.base.shiro.constants.ShiroConfigBean;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;
import java.util.Deque;
import java.util.LinkedList;

/**
 * session安全过滤器
 *
 * TODO 待测试
 *
 * @author liulei
 * @version 1.0
 */
public class SecuritySessionFilter extends AccessControlFilter {

    private static final String KICK_OUT_KEY = "kickout";

    /**
     * 踢出之前登录的/之后登录的用户 默认踢出之前登录的用户
     */
    private static boolean KICK_RULE = false;

    /**
     * shiro自定义配置
     */
    private ShiroConfigBean configBean;

    /**
     * 此处实际为RedisSessionManager
     */
    private SessionManager sessionManager;

    /**
     * Cache实现类与CacheManager的实现类一致，此处其实为RedisCache
     */
    private Cache<String, Deque<Serializable>> cache;

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        Subject subject = getSubject(request, response);
        String account = subject.toString();
        if (!subject.isAuthenticated() && !subject.isRemembered()) {
            //如果没有登录，直接进行之后的流程
            return true;
        }
        Session session = subject.getSession();
        Serializable sessionId = session.getId();
        //读取缓存   没有就存入
        Deque<Serializable> deque = cache.get(account);
        //如果此用户没有session队列，也就是还没有登录过，缓存中没有
        //就new一个空队列，不然deque对象为空，会报空指针
        if (deque == null) {
            deque = new LinkedList<>();
        }
        //如果队列里没有此sessionId，且用户没有被踢出；放入队列
        if (!deque.contains(sessionId) && session.getAttribute(KICK_OUT_KEY) == null) {
            //将sessionId存入队列
            deque.push(sessionId);
            //将用户的sessionId队列缓存
            cache.put(account, deque);
        }
        //如果队列里的sessionId数超出最大会话数，开始踢人
        while (deque.size() > configBean.getMaxSession()) {
            Serializable kickSessionId;
            if (KICK_RULE) {
                //踢出后者
                kickSessionId = deque.removeFirst();
            } else {
                //踢出前者
                kickSessionId = deque.removeLast();
            }
            // 更新缓存
            cache.put(account, deque);
            //获取被踢出的sessionId的session对象
            Session kickSession = sessionManager.getSession(new DefaultSessionKey(kickSessionId));
            if (kickSession != null) {
                //设置会话的kick属性表示踢出了
                kickSession.setAttribute(KICK_OUT_KEY, true);
            }
        }
        //如果被踢出了，直接退出，重定向到踢出后的地址
        if (session.getAttribute(KICK_OUT_KEY) != null && (Boolean) session.getAttribute(KICK_OUT_KEY)) {
            //剔除会话
            subject.logout();
            throw new ShiroUnAuthorizedException(HttpStatus.HTTP_FORBIDDEN, "您已经在其他地方登录，请重新登录！");
        }
        return true;
    }
}
